import React, { PureComponent } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Badge,
  Menu,
  Card,
  Icon,
  Form,
  DatePicker,
  Steps,
  Input,
  Radio,
  Select,
  Col,
  Row,
  Button,
  Dropdown,
  Modal,
  message,
  Tooltip,
  Avatar,
} from 'antd';

import ButtonGroup from 'antd/lib/button/button-group';

import { router } from 'umi';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Ellipsis from '@/components/Ellipsis';
import styles from './TeacherList.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;

const statusMap = ['default', 'processing', 'success'];
const status = ['离职', '出差中', '在校'];

// 职称
const academicTitles = {
  assistant: '助教',
  lecture: '讲师',
  adjunctProfessor: '副教授',
  professor: '教授',
};
// 学位
const academicDegrees = { doctor: '博士', postDoctor: '博士后' };
// 所属教学单位
const departments = {
  ch: '测绘中心实验室',
  yg: '遥感科学与技术系',
  zh: '资源环境与城乡规划管理系',
  cx: '土地资源管理系',
  dx: '测量工程系',
  tg: '地理信息科学系',
};

@Form.create()
class UpdateForm extends PureComponent {
  static defaultProps = {
    handleUpdate: () => {},
    handleUpdateModalVisible: () => {},
    values: {},
  };

  constructor(props) {
    super(props);
    this.state = {
      formVals: {
        name: props.values.name,
        description: props.values.description,
        department: props.values.department,
        academicTitle: props.values.academicTitle,
        academicDegree: props.values.academicDegree,
        status: props.values.status,
        createdAt: props.values.createdAt,
      },
      currentStep: 0,
    };

    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  handleNext = currentStep => {
    const { form, handleUpdate, values } = this.props;
    const { formVals: oldValue } = this.state;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formVals = { ...oldValue, ...fieldsValue };
      this.setState(
        {
          formVals,
        },
        () => {
          if (currentStep < 2) {
            this.forward();
          } else {
            handleUpdate({ id: values.id, ...formVals });
          }
        }
      );
    });
  };

  backward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep - 1,
    });
  };

  forward = () => {
    const { currentStep } = this.state;
    this.setState({
      currentStep: currentStep + 1,
    });
  };

  renderContent = (currentStep, formVals) => {
    const { form } = this.props;
    if (currentStep === 1) {
      return [
        <FormItem key="academicTitle" {...this.formLayout} label="职称">
          {form.getFieldDecorator('academicTitle', {
            initialValue: formVals.academicTitle,
          })(
            <Select style={{ width: '100%' }}>
              <Option value="assistant">助教</Option>
              <Option value="lecture">讲师</Option>
              <Option value="adjunctProfessor">副教授</Option>
              <Option value="professor">教授</Option>
            </Select>
          )}
        </FormItem>,
        <FormItem key="academicDegree" {...this.formLayout} label="学位">
          {form.getFieldDecorator('academicDegree', {
            initialValue: formVals.academicDegree,
          })(
            <Select style={{ width: '100%' }}>
              <Option value="doctor">博士</Option>
              <Option value="postDoctor">博士后</Option>
            </Select>
          )}
        </FormItem>,
        <FormItem key="department" {...this.formLayout} label="专业">
          {form.getFieldDecorator('department', {
            initialValue: formVals.department,
          })(
            <Select style={{ width: '100%' }}>
              {Object.keys(departments).map(key => (
                <Option value={key} key={key}>
                  {departments[key]}
                </Option>
              ))}
            </Select>
          )}
        </FormItem>,
      ];
    }
    if (currentStep === 2) {
      return [
        <FormItem key="createdAt" {...this.formLayout} label="入职时间">
          {form.getFieldDecorator('createdAt', {
            rules: [{ required: true, message: '请选择开始任职时间！' }],
          })(
            <DatePicker
              style={{ width: '100%' }}
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择入职时间"
            />
          )}
        </FormItem>,

        <FormItem key="status" {...this.formLayout} label="状态">
          {form.getFieldDecorator('status', {
            initialValue: formVals.status,
          })(
            <RadioGroup>
              <Radio value="0">离职</Radio>
              <Radio value="1">出差中</Radio>
              <Radio value="2">在校</Radio>
            </RadioGroup>
          )}
        </FormItem>,
      ];
    }
    return [
      <FormItem key="name" {...this.formLayout} label="姓名">
        {form.getFieldDecorator('name', {
          rules: [{ required: true, message: '请输入姓名！' }],
          initialValue: formVals.name,
        })(<Input placeholder="请输入" />)}
      </FormItem>,
      <FormItem key="description" {...this.formLayout} label="描述">
        {form.getFieldDecorator('description', {
          rules: [{ required: true, message: '请输入至少五个字符的描述信息！', min: 5 }],
          initialValue: formVals.description,
        })(<TextArea rows={4} placeholder="请输入至少五个字符" />)}
      </FormItem>,
    ];
  };

  renderFooter = currentStep => {
    const { handleUpdateModalVisible, values } = this.props;
    if (currentStep === 1) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible(false, values)}>
          取消
        </Button>,
        <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
          下一步
        </Button>,
      ];
    }
    if (currentStep === 2) {
      return [
        <Button key="back" style={{ float: 'left' }} onClick={this.backward}>
          上一步
        </Button>,
        <Button key="cancel" onClick={() => handleUpdateModalVisible(false, values)}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={() => this.handleNext(currentStep)}>
          完成
        </Button>,
      ];
    }
    return [
      <Button key="cancel" onClick={() => handleUpdateModalVisible(false, values)}>
        取消
      </Button>,
      <Button key="forward" type="primary" onClick={() => this.handleNext(currentStep)}>
        下一步
      </Button>,
    ];
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible, values } = this.props;
    const { currentStep, formVals } = this.state;

    return (
      <Modal
        width={640}
        bodyStyle={{ padding: '32px 40px 48px' }}
        destroyOnClose
        title="教师信息修改"
        visible={updateModalVisible}
        footer={this.renderFooter(currentStep)}
        onCancel={() => handleUpdateModalVisible(false, values)}
        afterClose={() => handleUpdateModalVisible()}
      >
        <Steps style={{ marginBottom: 28 }} size="small" current={currentStep}>
          <Step title="基本信息" />
          <Step title="学历" />
          <Step title="状态" />
        </Steps>
        {this.renderContent(currentStep, formVals)}
      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ teachers, loading }) => ({
  teachers,
  loading: loading.models.teachers,
}))
@Form.create()
class TeacherList extends PureComponent {
  state = {
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
  };

  columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      onCell: () => {
        return {
          style: {
            whiteSpace: 'nowrap',
            maxWidth: 100,
          },
        };
      },
      render: (text, record) => (
        <a onClick={() => this.previewItem(record.id)}>
          <Avatar
            style={{ top: -2, verticalAlign: 'middle', marginRight: 8 }}
            src={record.avatar}
            size="small"
          />
          {text}
        </a>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      textWrap: 'ellipsis',
      onCell: () => {
        return {
          style: {
            whiteSpace: 'wrap',
            maxWidth: 300,
          },
        };
      },
      render: text => (
        <Tooltip title={text}>
          <Ellipsis className={styles.item} lines={3}>
            {text}
          </Ellipsis>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      onCell: () => {
        return {
          style: {
            whiteSpace: 'nowrap',
            maxWidth: 100,
          },
        };
      },
      filters: [
        {
          text: status[0],
          value: 0,
        },
        {
          text: status[1],
          value: 1,
        },
        {
          text: status[2],
          value: 2,
        },
      ],
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '教学单位',
      dataIndex: 'department',
      filters: [
        {
          text: departments.ch,
          value: 'ch',
        },
        {
          text: departments.yg,
          value: 'yg',
        },
        {
          text: departments.zh,
          value: 'zh',
        },
        {
          text: departments.dx,
          value: 'dx',
        },
        {
          text: departments.cx,
          value: 'cx',
        },
        {
          text: departments.tg,
          value: 'tg',
        },
      ],
      render(val) {
        return <span>{departments[val]}</span>;
      },
    },
    {
      title: '职称',
      dataIndex: 'academicTitle',
      filters: [
        {
          text: academicTitles.assistant,
          value: 'assistant',
        },
        {
          text: academicTitles.lecture,
          value: 'lecture',
        },
        {
          text: academicTitles.adjunctProfessor,
          value: 'adjunctProfessor',
        },
        {
          text: academicTitles.professor,
          value: 'professor',
        },
      ],
      render(val) {
        return <span>{academicTitles[val]}</span>;
      },
    },
    {
      title: '学位',
      dataIndex: 'academicDegree',
      filters: [
        {
          text: academicDegrees.doctor,
          value: 'doctor',
        },
        {
          text: academicDegrees.postDoctor,
          value: 'postDoctor',
        },
      ],
      render(val) {
        return <span>{academicDegrees[val]}</span>;
      },
    },
    {
      title: '入职时间',
      dataIndex: 'createdAt',
      sorter: true,
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      render: (text, record) => (
        <ButtonGroup>
          <Button onClick={() => this.previewItem(record.id)}>
            <Icon type="eye" />
          </Button>
          <Button onClick={() => this.handleUpdateModalVisible(true, record)}>
            <Icon type="edit" />
          </Button>
          <Button onClick={() => this.handleRemove(record.key)}>
            <Icon type="delete" />
          </Button>
        </ButtonGroup>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'teachers/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const getValue = obj =>
      Object.keys(obj)
        .map(key => obj[key])
        .join(',');

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'teachers/fetch',
      payload: params,
    });
  };

  // 查看教师详情
  previewItem = id => {
    router.push(`/teachers/${id}`);
  };

  // 重置筛选项
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'teachers/fetch',
      payload: {},
    });
  };

  // 更多筛选
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (selectedRows.length === 0) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'teachers/remove',
          payload: {
            key: selectedRows.map(row => row.key),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'teachers/fetch',
        payload: values,
      });
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      stepFormValues: record || {},
    });
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    dispatch({
      type: 'teachers/update',
      payload: {
        query: formValues,
        body: fields,
      },
    });

    message.success('更新成功');
    this.handleUpdateModalVisible();
  };

  handleRemove = key => {
    const { dispatch } = this.props;
    dispatch({
      type: 'teachers/remove',
      payload: {
        key: [key],
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名">
              {getFieldDecorator('name')(<Input placeholder="请输入姓名" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">离职</Option>
                  <Option value="1">出差中</Option>
                  <Option value="2">在校</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名">
              {getFieldDecorator('name')(<Input placeholder="请输入姓名" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">离职</Option>
                  <Option value="1">出差中</Option>
                  <Option value="2">在校</Option>
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="专业">
              {getFieldDecorator('department')(
                <Select style={{ width: '100%' }}>
                  {Object.keys(departments).map(key => (
                    <Option value={key} key={key}>
                      {departments[key]}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>

        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="职称">
              {getFieldDecorator('academicTitle')(
                <Select style={{ width: '100%' }}>
                  <Option value="assistant">助教</Option>
                  <Option value="lecture">讲师</Option>
                  <Option value="adjunctProfessor">副教授</Option>
                  <Option value="professor">教授</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="学位">
              {getFieldDecorator('academicDegree')(
                <Select style={{ width: '100%' }}>
                  <Option value="doctor">博士</Option>
                  <Option value="postDoctor">博士后</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      teachers: { data },
      loading,
    } = this.props;
    const { selectedRows, updateModalVisible, stepFormValues } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );

    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };

    return (
      <PageHeaderWrapper title="教师列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button
                icon="plus"
                type="primary"
                onClick={() => {
                  router.push('/teachers/create');
                  // this.handleModalVisible(true);
                }}
              >
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button>批量操作</Button>
                  <Dropdown overlay={menu}>
                    <Button>
                      更多操作 <Icon type="down" />
                    </Button>
                  </Dropdown>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>

        {stepFormValues && Object.keys(stepFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={stepFormValues}
          />
        ) : null}
      </PageHeaderWrapper>
    );
  }
}

export default TeacherList;
